package com.xianzhi.controller;

import com.xianzhi.model.UserEntity;
import com.xianzhi.repository.UserRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class MainController {
    @Autowired
    private UserRespository userRespository;
    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String index(){
        return "index";
    }
  //查询所有用户
    @RequestMapping(value = "/admin/users", method=RequestMethod.GET)
    public String getUsers(ModelMap modelMap){
        //调用持久层的方法查询所有用户的信息
        List<UserEntity> list = userRespository.findAll();
        //将查询到的list把存到ModelMap里
        modelMap.addAttribute("userList",list);
        return "admin/users";
    }

    //增加
    @RequestMapping(value = "admin/addUser",method = RequestMethod.GET)
    public String insertUser(){
        return "admin/addUser";
    }
    //添加用户信息
    @RequestMapping(value = "/admin/users/addP",method = RequestMethod.POST)
    public String addUserPost(@ModelAttribute("user") UserEntity userEntity){
        userRespository.saveAndFlush(userEntity);
                return "redirect:/admin/users";
    }
    //根据id删除用户的信息
    //restful风格：就是一种设计的风格（设计原则或约束条件），而不是标准
    //每一个URI代表一种资源
    //客户端和服务器之间，传递这种资源的某种表现形式
    //客户端通过四个http动作对服务器的资源进行操作
    //Get(Select)从服务器取出资源
    //Post(Create) 在服务器端创建资源
    //Put(update) 在服务器端更新资源
    //Delete（delete）从服务器删除资源
    @RequestMapping(value = "/admin/users/delete/{id}",method = RequestMethod.GET)
    public String deleteUser(@PathVariable("id")Integer userId){
        userRespository.delete(userId);
        userRespository.flush();
        return "redirect:/admin/users";
    }
    //删除
    @RequestMapping(value = "/deleteById")
    public String deleteById(@RequestParam(value = "id") Integer id) {
        userRespository.delete(id);
        return "redirect:admin/users";
    }
    //调回主菜单

    //修改用户信息
    @RequestMapping(value = "/admin/users/update/{id}",method = RequestMethod.GET)
    public String updateById(@PathVariable("id")Integer userId,ModelMap modelMap){
        UserEntity userEntity = userRespository.findOne(userId);
        modelMap.addAttribute("user",userEntity);
        return "admin/updateUser";

    }


}
